package com.sjgl.esdn.utils;

import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPage;
//import fr.opensagres.poi.xwpf.converter.pdf.PdfConverter;
//import fr.opensagres.poi.xwpf.converter.pdf.PdfOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.ConnectException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;


/**
 * word转pdf,（转pdf需要window环境，推荐使用OpenOfficeUtils类）
 *
 * @author 缪恒铭
 * @date 2022/08/15
 */
public class Word2PdfESDN {
    private static final Integer WORD_TO_PDF_OPERAND = 17;
    private static final Integer PPT_TO_PDF_OPERAND = 32;
    private static final Integer EXCEL_TO_PDF_OPERAND = 0;

    /**
     * doc转pdf
     *
     * @param srcFilePath src文件路径
     * @param pdfFilePath pdf文件路径
     * @throws Exception 异常
     */
    public static void doc2pdf(String srcFilePath, String pdfFilePath) throws Exception {
        ActiveXComponent app = null;
        Dispatch doc = null;
        try {
            ComThread.InitSTA();
            app = new ActiveXComponent("Word.Application");
            app.setProperty("Visible", false);
            Dispatch docs = app.getProperty("Documents").toDispatch();
            Object[] obj = new Object[]{
                    srcFilePath,
                    new Variant(false),
                    new Variant(false),//是否只读
                    new Variant(false),
                    new Variant("pwd")
            };
            doc = Dispatch.invoke(docs, "Open", Dispatch.Method, obj, new int[1]).toDispatch();
//          Dispatch.put(doc, "Compatibility", false);  //兼容性检查,为特定值false不正确
            Dispatch.put(doc, "RemovePersonalInformation", false);
            Dispatch.call(doc, "ExportAsFixedFormat", pdfFilePath, WORD_TO_PDF_OPERAND); // word保存为pdf格式宏，值为17

        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            if (doc != null) {
                Dispatch.call(doc, "Close", false);
            }
            if (app != null) {
                app.invoke("Quit", 0);
            }
            ComThread.Release();
        }
    }

    /**
     * ppt转pdf
     *
     * @param srcFilePath src文件路径
     * @param pdfFilePath pdf文件路径
     * @throws Exception 异常
     */
    public static void ppt2pdf(String srcFilePath, String pdfFilePath) throws Exception {
        ActiveXComponent app = null;
        Dispatch ppt = null;
        try {
            ComThread.InitSTA();
            app = new ActiveXComponent("PowerPoint.Application");
            Dispatch ppts = app.getProperty("Presentations").toDispatch();

            /*
             * call
             * param 4: ReadOnly
             * param 5: Untitled指定文件是否有标题
             * param 6: WithWindow指定文件是否可见
             * */
            ppt = Dispatch.call(ppts, "Open", srcFilePath, true, true, false).toDispatch();
            Dispatch.call(ppt, "SaveAs", pdfFilePath, PPT_TO_PDF_OPERAND); // ppSaveAsPDF为特定值32

        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            if (ppt != null) {
                Dispatch.call(ppt, "Close");
            }
            if (app != null) {
                app.invoke("Quit");
            }
            ComThread.Release();

        }
    }

    /**
     * excel转pdf
     *
     * @param inFilePath  在文件路径
     * @param outFilePath 从文件路径
     * @return boolean
     * @throws Exception 异常
     */
    public static boolean excel2Pdf(String inFilePath, String outFilePath) throws Exception {
        ActiveXComponent ax = null;
        Dispatch excel = null;
        try {
            ComThread.InitSTA();
            ax = new ActiveXComponent("Excel.Application");
            ax.setProperty("Visible", new Variant(false));
            ax.setProperty("AutomationSecurity", new Variant(3)); // 禁用宏

            Dispatch excels = ax.getProperty("Workbooks").toDispatch();

            Object[] obj = new Object[]{
                    inFilePath,
                    new Variant(false),
                    new Variant(false)
            };
            excel = Dispatch.invoke(excels, "Open", Dispatch.Method, obj, new int[9]).toDispatch();
            //将excel表格 设置成A3的大小
            Dispatch sheets = Dispatch.call(excel, "Worksheets").toDispatch();
            Dispatch sheet = Dispatch.call(sheets, "Item", new Integer(1)).toDispatch();
            Dispatch pageSetup = Dispatch.call(sheet, "PageSetup").toDispatch();
            Dispatch.put(pageSetup, "PaperSize", new Integer(8));//A3是8，A4是9，A5是11等等

            // 转换格式
            Object[] obj2 = new Object[]{
                    new Variant(EXCEL_TO_PDF_OPERAND), // PDF格式=0
                    outFilePath,
                    new Variant(0)  //0=标准 (生成的PDF图片不会变模糊) ; 1=最小文件
            };
            Dispatch.invoke(excel, "ExportAsFixedFormat", Dispatch.Method, obj2, new int[1]);

        } catch (Exception es) {
            es.printStackTrace();
            return false;
            // throw es;
        } finally {
            if (excel != null) {
                Dispatch.call(excel, "Close", new Variant(false));
            }
            if (ax != null) {
                ax.invoke("Quit", new Variant[]{});
                ax = null;
            }
            ComThread.Release();
        }
        return true;

    }

    /**
     * word转pdf（几种方法的整合,返回pdf文件路径）
     *
     * @param inFilePath  在文件路径
     * @param outFilePath 从文件路径
     * @return boolean
     */
    public static boolean word2pdf(String inFilePath, String outFilePath) {
        try {
            String suffix = inFilePath.substring(inFilePath.lastIndexOf('.') + 1);
            switch (suffix) {
                case "docx":
                case "doc":
                    doc2pdf(inFilePath, outFilePath);
                    break;
                case "pptx":
                case "ppt":
                    ppt2pdf(inFilePath, outFilePath);
                    break;
                case "xlsx":
                case "xls":
                    excel2Pdf(inFilePath, outFilePath);
                    break;
                default:
                    break;
            }
        } catch (Exception e) {
            return true;
        }
        return true;
    }

    /**
     * pdf转预览图（首页截图）
     *
     * @param inFilePath  源
     * @param outFilePath 从文件路径
     * @return boolean
     */
    public static boolean pdf2preview(String inFilePath, String outFilePath) {
        File file = new File(inFilePath);
        if (!file.exists()) {
            System.err.println("路径[" + inFilePath + "]对应的pdf文件不存在!");
            return false;
        }
        try {
            RandomAccessFile raf = new RandomAccessFile(file, "r");
            FileChannel channel = raf.getChannel();
            ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
            PDFFile pdffile = new PDFFile(buf);
            PDFPage page = pdffile.getPage(0);
            // get the width and height for the doc at the default zoom
            Rectangle rect = new Rectangle(0, 0, (int) page.getBBox()
                    .getWidth(), (int) page.getBBox().getHeight());
            // generate the image
            Image img = page.getImage(rect.width, rect.height, // width &
                    rect, // clip rect
                    null, // null for the ImageObserver
                    true, // fill background with white
                    true // block until drawing is done
            );
            BufferedImage tag = new BufferedImage(rect.width, rect.height, BufferedImage.TYPE_INT_RGB);
            tag.getGraphics().drawImage(img, 0, 0, rect.width, rect.height, null);

            String dstName = outFilePath;
            String formatName = dstName.substring(dstName.lastIndexOf(".") + 1);
//                System.out.println(formatName);//
//                System.out.println(dstName);//
            ImageIO.write(tag, /*"GIF"*/ formatName /* format desired */, new File(dstName) /* target */);
            return true;
        } catch (Exception e) {
            return true;
        }
    }



    /**
     * pdf在线预览
     *
     * @param source 源
     * @param target 目标
     * @return boolean
     */
    public static boolean createScreenShoot(String source, String target) {
        File file = new File(source);
        if (!file.exists()) {
            System.err.println("路径[" + source + "]对应的pdf文件不存在!");
            return false;
        }
        try {
            RandomAccessFile raf = new RandomAccessFile(file, "r");
            FileChannel channel = raf.getChannel();
            ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
            PDFFile pdffile = new PDFFile(buf);
            int num = pdffile.getNumPages();
            for (int i = 1; i <= num; i++) {
                PDFPage page = pdffile.getPage(i);
                // get the width and height for the doc at the default zoom
                Rectangle rect = new Rectangle(0, 0, (int) page.getBBox()
                        .getWidth(), (int) page.getBBox().getHeight());
                // generate the image
                Image img = page.getImage(rect.width, rect.height, // width &
                        rect, // clip rect
                        null, // null for the ImageObserver
                        true, // fill background with white
                        true // block until drawing is done
                );
                BufferedImage tag = new BufferedImage(rect.width, rect.height, BufferedImage.TYPE_INT_RGB);
                tag.getGraphics().drawImage(img, 0, 0, rect.width, rect.height, null);

                String dstName = target + i + "." + "jpg";
                String formatName = dstName.substring(dstName.lastIndexOf(".") + 1);
                System.out.println(formatName);//
                System.out.println(dstName);//
                ImageIO.write(tag, /*"GIF"*/ formatName /* format desired */, new File(dstName) /* target */);
            }
            return true;
        } catch (Exception e) {
            return true;
        }
    }


    public static void main(String[] args) throws Exception {
//        doc2pdf("E:\\1.doc","E:\\5.pdf");
//        String source = "E:\\5.pdf";
//        String target = "E:\\新建文件夹\\";
//        createScreenShoot(source,target);
        for (int i = 1; i <= 4; i++) {
            pdf2preview("E:\\" + i + ".pdf", "E:\\" + i + ".jpg");
        }

    }
}